<?php
// only local requests
$ip = $_SERVER['REMOTE_ADDR'];
$test = explode('.',$ip);
$loc =  range(17,32);

if ($test[0] == '192' || $test[0] == '10' || $ip = '127.0.0.1' || $test[0] == '172' && in_array($test[1],$loc)) {	
	include_once(getcwd().'/includes/functions.php');

	if (isset($_GET['config']) && $_GET['config'] == 'true') {
		include_once(getcwd().'/includes/connection.php');

		if (isset($_GET['getfolders']) && $_GET['getfolders'] == 'true') {
			$result = mysql_query("SELECT * FROM config ORDER BY id ASC");

			while($row = mysql_fetch_array($result)) {
				if($row['music'] != true) {
					$row['music'] = 'false';
				}

				if($row['video'] != true) {
					$row['video'] = 'false';
				}

				$video = trim($row['video']);
				$music = trim($row['music']);
				echo $music." ".$video." ";
			}

			die;
		} else {
			$music = 'false';
			$video = 'false';
			
			if(isset($_GET['music']) && $_GET['music']  == 'true') {
				$music = 'true';
				$music = trim(mysql_prep($music));
			} else if(isset($_GET['video']) && $_GET['video'] == 'true') {
				$video = 'true';
				$video = trim(mysql_prep($video));
			}

			$folder = trim(mysql_prep($_GET['folder']));
			$query = "UPDATE config SET music = '{$music}', video = '{$video}' WHERE id = '{$folder}'";
			$result = mysql_query($query, $connection);
			
			if(!$result) {
				mysql_error();
			}

			die;
		}
	} else if(isset($_GET['setup']) && $_GET['setup'] == 'true') {
		$sFile = getcwd().'/includes/settings.php';
		$fh = fopen($sFile,'w') or die("Can't open file");
		$data = "<?php\n";
		fwrite($fh,$data);
		$server = $_GET['server'];
		$data = "define('SERVER','$server');\n";
		fwrite($fh,$data);
		$jukebox = $_GET['juke'];
		$data = "define('JUKE','$jukebox');\n";
		fwrite($fh,$data);
		$db_server = $_GET['db_server'];
		$data = "define('DB_SERVER','$db_server');\n";
		fwrite($fh,$data);
		$db_user = $_GET['db_user'];
		$data = "define('DB_USER','$db_user');\n";
		fwrite($fh,$data);
		$db_name = $_GET['db_name'];
		$data = "define('DB_NAME','$db_name');\n";
		fwrite($fh,$data);
		$db_pass = $_GET['db_pass'];
		$data = "define('DB_PASS','$db_pass');\n";
		fwrite($fh,$data);
		$s_user = $_GET['s_user'];
		$s_pass = $_GET['s_pass'];
		$data = "define('CREDS','u=$s_user&p=$s_pass&v=1.2.0&c=bologna');\n";
		fwrite($fh,$data);
		$data = "\n?>";
		
		fwrite($fh,$data);
		die;	
	} else if (isset($_GET['scanfolders']) && $_GET['scanfolders'] == 'true') {
		include_once(getcwd().'/includes/connection.php');
		$result = mysql_query("TRUNCATE config") or die(mysql_error());
		$file = JUKE."rest/getMusicFolders.view?".CREDS;
		$arr = my_xml2array($file);
		$i=0;
		while ($i<count($arr[0][0])-1)  {	
			$id = $arr[0][0][$i]['attributes']['id'];
			$result = mysql_query("INSERT into config (id) VALUES('{$id}')") or die(mysql_error());
			$i++;
		}
		
		die;
	} else if (isset($_GET['rescan']) && $_GET['rescan'] == 'true') {
		include_once(getcwd().'/includes/settings.php');
		$file = JUKE."rest/getMusicFolders.view?".CREDS;
		$arr = my_xml2array($file);
		$i=0;

		while ($i<count($arr[0][0])-1)  {
			$id = $arr[0][0][$i]['attributes']['id'];
			$name = $arr[0][0][$i]['attributes']['name'];
			echo	"<div style='margin:3px; width:350px;'>
						<div style='float:left; width:155px;' class='musicfolderid'>$name($id)</div>
						<div style='float:right;'>
							<input name='type$i' type='radio' class='music'>Music</input>
							<input name='type$i' type='radio' class='video'>Video</input>
						</div>
					</div>";
			$i++;
		}
	
		die;
	} else if (isset($_GET['createtable']) && $_GET['createtable'] == 'true') {
		include_once(getcwd().'/includes/settings.php');
		$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
		$result3 = mysql_query("CREATE DATABASE ".DB_NAME);
		mysql_select_db(DB_NAME,$connection);

		$username = trim($_GET['username']);
		$password = trim($_GET['password']);
		$hashed_password = sha1($password);
		
		
		
		$result = mysql_query("CREATE TABLE `users` (
			`id` int(11) NOT NULL AUTO_INCREMENT,
			`username` varchar(255) DEFAULT NULL,
			`hashed_password` varchar(255) DEFAULT NULL,
			`shuffle` tinyint(1) DEFAULT '0',
			`timestamp` tinyint(1) DEFAULT '0',
			`reap` tinyint(1) DEFAULT '0',
			`current` varchar(255) NOT NULL DEFAULT '',
			`currentsong` varchar(255) NOT NULL,
			`currentid` varchar(255) NOT NULL,
			`duration` varchar(5) NOT NULL,
			`cover` varchar(255) NOT NULL,
			`admin` tinyint(1) NOT NULL DEFAULT '0',
			PRIMARY KEY (`id`)
		) ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=ascii") or die(mysql_error());
		
		$result1 = mysql_query("CREATE TABLE `config` (
			`id` int(11) NOT NULL,
			`music` varchar(32) NOT NULL,
			`video` varchar(32) NOT NULL,
			PRIMARY KEY (`id`)
		) ENGINE=MyISAM DEFAULT CHARSET=ascii") or die(mysql_error());
		
		$result2 = mysql_query("INSERT INTO users (
			username, hashed_password,admin
		) VALUES (
			'{$username}', '{$hashed_password}','1'
		)");
		
		$result4 = mysql_query("TRUNCATE config") or die(mysql_error());
		$file = JUKE."rest/getMusicFolders.view?".CREDS;
		$arr = my_xml2array($file);
		$i=0;
		
		while ($i<count($arr[0][0])-1)  {	
			$id = $arr[0][0][$i]['attributes']['id'];
			$result = mysql_query("INSERT into config (id) VALUES ('{$id}')") or die(mysql_error());
			$i++;
		}
						
		die;
	}
	
	echo	"<html>
				<head>
					<title>Supersonic Setup</title>
					<link type='text/css' href='css/setup.css' rel='stylesheet' />
					<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
					<link type='text/css' href='css/custom-theme/jquery-ui-1.8.2.custom.css' rel='stylesheet' />	
					<script type='text/javascript' src='js/jquery-ui-1.8.2.custom.min.js'></script>
					<script type='text/javascript' src='js/setup.js'></script>
				</head>
				<body color='#fff' bgcolor='#000'>
					<div id='hint'></div>
					<div id='container'>
						<div id='menu'>
							<span style='display:inline; font-size:20px; float:left;'>
								<img src='img/subsonic.png' />
								<span style='position:relative; font-size:20px; top:-8px;'> Setup</span>
							</span>
							<button id='foldersetup'>3. configure folders</button>
							<button id='createtable'>2. create db/tables</button>
							<button id='setup'>1. run basic setup</button>
	
						</div>
						<div id='main'>";
	
	if (is_file(getcwd().'/includes/settings.php')) {        
		include_once(getcwd().'/includes/settings.php');

		if (SERVER == '' || JUKE == '' || DB_NAME == '' || DB_USER == '' || DB_PASS == '' || CREDS == '' || DB_SERVER == '') {
			// Security hole in javascript
			echo	"<script type='text/javascript'>\n
						function fillConfig() {
							$('#db_name').val('".DB_NAME."');\n
							$('#juke').val('".JUKE."');\n
							$('#server').val('".SERVER."');\n
							$('#db_server').val('".DB_SERVER."');\n
							$('#db_user').val('".DB_USER."');\n
							$('#db_pass').val('".DB_PASS."');\n
						}\n
						
						$(document).ready(function() {\n
							$('#status').html(\"There seems to be an issue with some variables, please rerun basic setup.\");\n
							$('#hint').position({ my:'left top',at:'left bottom',of:'#setup',offset:'0 5' }).css('width','112px');\n
						});\n
					</script>";
		} else {
			include_once getcwd().'/includes/connection.php';
			$result = mysql_query("SELECT * from users");
			
			if(!$result) {
				echo	"<img src='img/x.gif' />
						Connected to MySQL server, but users table not created. Hit 'create db/tables' above ^
						<br />
						<script type='text/javascript'>
							$(document).ready(function() {
								$('#hint').position({my:'left top',at:'left bottom', of:'#createtable', offset:'0 3',collision:'fit'});\n
							});\n
						</script>";
			} else {
				echo	"<img src='img/check.gif' />
						Connected to MySQL Server, users table exists.
						<br />
						<script type='text/javascript'>
							$(document).ready(function() {
								$('#hint').position({my:'left top', at:'left bottom', of:'#foldersetup', offset:'1 3', collision:'fit'});\n
							});\n
						</script>";
			}
			
			$file = JUKE."rest/ping.view?".CREDS;
			$arr = my_xml2array($file);
			
			if($arr[0]['attributes']['status'] == 'ok') {
				echo "<img src='img/check.gif' /> Connection to Subsonic server OK<hr size='1' />";
			} else {
				echo "<img src='img/x.gif' /> Connection to Subsonic server failed. ";
			}
			
			echo	"Local server ip/port:".SERVER."<br />
					MySQL server(local address):".DB_SERVER."<br />
					Subsonic server/port:".JUKE."<br />
					<hr size='1'>
					Database name:".DB_NAME."<br />
					Database username:".DB_USER."<br />
					Database password:".DB_PASS."<br />
					<hr size='1'>";
			
			$a = explode('&', CREDS);
			$i = 0;
			
			while ($i < count($a)) {
				$b = explode('=', $a[$i]);

				//if -> switch/case
				if($i == 0) {
					$username = $b[1];
					echo "Subsonic username:".htmlspecialchars(urldecode($b[1]))."<br />";
				}
				if($i == 1) {
					$password = $b[1];
					echo "Subsonic password:".htmlspecialchars(urldecode($b[1]))."<br />";
				}
				if($i == 2) {
					echo "API Version:".htmlspecialchars(urldecode($b[1]))."<br />";
				}
				if($i == 3) {
					echo "Player name:".htmlspecialchars(urldecode($b[1]))."<br />";
				}
				
				$i++;
			}

			if ($username != '' && $password != '' && defined('SERVER') && defined('JUKE') && defined('DB_NAME') && defined('DB_USER') && defined('DB_PASS') && defined('CREDS') && defined('DB_SERVER')) {
				echo	"<script type='text/javascript'>\n
							function fillConfig() {
								$('#db_name').val('".DB_NAME."');\n
								$('#juke').val('".JUKE."');\n
								$('#server').val('".SERVER."');\n
								$('#db_server').val('".DB_SERVER."');\n
								$('#db_user').val('".DB_USER."');\n
								$('#db_pass').val('".DB_PASS."');\n
							}\n
							
							$(document).ready(function() {\n
								$('#status').html(\"<span>Script variables look setup, create the database if you haven't already, then configure your music/video folders\");\n
							});\n
						</script>";
			} else {
				echo	"<script type='text/javascript'>\n
							function fillConfig() {
								$('#db_name').val('".DB_NAME."');\n
								$('#juke').val('".JUKE."');\n
								$('#server').val('".SERVER."');\n
								$('#db_server').val('".DB_SERVER."');\n
								$('#db_user').val('".DB_USER."');\n
								$('#db_pass').val('".DB_PASS."');\n
							}\n
							
							$(document).ready(function() {\n
								$('#status').html(\"There seems to be an issue with some variables, please rerun basic setup.\");\n
							});\n
						</script>";
			}
		}
	} else {
		echo	"Settings.php not found, please run basic setup.
				<script type='text/javascript'>
					$(document).ready(function() {
						$('#hint').position({ my:'left top',at:'left bottom',of:'#setup',offset:'0 5' }).css('width','112px');\n
					});\n
				</script>";
	}

	echo	"</div>
			<div id='status'></div>";

	
	echo	"<div id='foldersetupd'>
			<div id='folders'>";

	$file = JUKE."rest/getMusicFolders.view?".CREDS;
	$arr = my_xml2array($file);
	$i=0;
	
	while ($i<count($arr[0][0])-1)  {
		$id = $arr[0][0][$i]['attributes']['id'];
		$name = $arr[0][0][$i]['attributes']['name'];
		
		echo	"<div style='margin:3px; padding:1px; width:350px;'>
					<div style='float:left; width:300px;' class='musicfolderid' id='$id'>$name($id)
						<div style='float:right;'>
							<input name='type$id' type='radio' class='music'>Music</input>
							<input name='type$id' type='radio' class='video'>Video</input>
						</div>
					</div>
				</div>";

		$i++;
	}
	
	echo	"</div>
			</div>
			<div id='warn'>This will delete all user logins, preferences, and folder configs for the frontend
				<div class='line'><label for='a_user'>Admin Username</label><input type='text' id='a_user' /></div>
				<div class='line'><label for='a_pass'>Admin Pass</label><input type='text' id='a_pass' /></div>
			</div>";

	echo	"<div id='setupd'>
				<div class='line'>
					<div class='text'>Server (ex> http://ip:port/)</div>
					<input type='text' id='server' value='http://' />
				</div>
				<div class='line'>
					<div class='text'>MySql server(local address)</div>
					<input type='text' id='db_server' />
				</div>
				<div class='line'>
					<div class='text'>Subsonic server (ex> http://ip:port/)</div>
					<input type='text' id='juke' value='http://' />
				</div>
				<div class='line'>
					<div class='text'>Database name</div>
					<input type='text' id='db_name' />
				</div>
				<div class='line'>
					<div class='text'>Database user</div>
					<input type='text' id='db_user' />
				</div>
				<div class='line'>
					<div class='text'>Database password</div>
					<input type='text' id='db_pass' />
				</div>
				<div class='line'>
					<div class='text'>Subsonic username</div>
					<input type='text' id='s_user' />
				</div>
				<div class='line'>
					<div class='text'>Subsonic password</div>
					<input type='text' id='s_pass' />
				</div>
			</div>
			</div>
			</body>
			</html>";
	
} else {
	die(header("Location: /"));
}
?>

